'use strict';

const log = require('@imooc-cli-dev/log');
const semver = require('semver')
const colors = require('colors')

const constant = {
  LOWEST_NODE_VERSION: '12.0.0'
}

class command {
  constructor(argv) {
    if(!argv) {
      throw new Error('args 不可为空')
    }

    if(!Array.isArray(argv)) {
      throw new Error('args必须为数组')
    }

    if(argv.length < 1) {
      throw new Error('args参数数量必须大于1')
    }


    this._argv = argv;
    let runner = new Promise((resolve, reject)=> {
      let chain = Promise.resolve();
      chain = chain.then(res => this.checkNodeVersion())
      chain = chain.then(res => this.initArgs())
      chain = chain.then(res => this.init())
      chain = chain.then(res => this.exec())

      chain.catch(error => {
        log.error(colors.red(error.message))
      })
    })

  }

  initArgs() {
    this._cmd = this._argv[this._argv.length - 1];
    this._argv = this._argv.slice(0, this._argv.length - 1)
  }

  init() {
    throw new Error('init 必须实现')
  }

  exec() {
    throw new Error('exec 必须实现')
  }

  checkNodeVersion() {
    // 获取当前node版本
    const currentVersion = process.version;
    const lowestVersion = constant.LOWEST_NODE_VERSION;
    if(semver.lt(currentVersion, lowestVersion)) {
      throw new Error(colors.red('请升级node版本至' + lowestVersion))
    }
  }
}

module.exports = command;
